package com.neusoft.neuiotms.sap;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UrlFilter implements Filter {

    private final String services;

    public UrlFilter(String services) {
        this.services = services;
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final String path = httpRequest.getRequestURI();
        if (UrlFilter.log.isDebugEnabled()) {
            UrlFilter.log.debug("filter url {}", path);
        }
        if (Pattern.matches("^/(" + this.services + ").*", path)) {
            httpRequest.getRequestDispatcher(path.replaceAll("^/(" + this.services + ")", "")).forward(request,
                    response);
        } else {
            chain.doFilter(request, response);
        }
        return;

    }
}
